const http = require("http")
const fs = require("fs")
const url = require("url")
const querystring = require("querystring")
const {
    dateFormat
} = require("./date")

const server = http.createServer()
server.on("request", (req, res) => {
    console.log(req.url);
    // 把字符串变为 对象  就可以方便的取出传递过来的数据了
    let { pathname } = url.parse(req.url)
    console.log(pathname);
    if (pathname == "/login") {
        fs.readFile("./post.html", "utf8", (err, data) => {
            if (err) {
                res.writeHead(404, "not found", {
                    "Content-Type": "text/html;charset=utf-8"
                })
                res.end("<h2>您要访问的页面走丢了</h2>")
            }
            res.end(data)
        })
    }
    if (pathname == "/index") {
        res.writeHead(200, "success", {
            "Content-Type": "text/plain;charset=utf-8"
        })
        if (req.method.toLowerCase() == "post") {
            let = reqBody = ""
            // post数据开始传输会触发data回调
            req.on("data", data => {
                // console.log("123",data);
                // console.log("456",decodeURIComponent(data));
                // 转码 二进制变为字符串
                decodeURIComponent(data)
                reqBody += data
            })
            // post数据传输完毕会触发end回调
            req.on("end", () => {
                // 字符串转变为对象
                let dataObj = querystring.parse(reqBody.toString());
                console.log(dataObj);
                res.write(
                    `欢迎${dataObj.username}登录,登录密码是:${dataObj.password},登录时间是:${dateFormat(new Date())}`
                );
                res.end()
            })
        }else{
            res.writeHead(404, "not found", {
                "Content-Type": "text/html;charset=utf-8"
            })
            res.end("<h2>您要访问的页面走丢了</h2>")
        }
    }
})
server.listen(8080, () => {
    console.log("服务已经成功创建在8080端口");
})